package com.demo.commons.exception;

import com.demo.commons.DTO.ExResult;
import com.demo.commons.exception.customize.BusinessExceptionR;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 *@author zwy
 *@date 2023/7/20 5:10
 * 全局异常处理 当出现异常后捕获并且统一返回给前端
 * RestControllerAdvice:不会使用视图返回
 *  权限校验
 *  请求方式     ajax
 *  系统异常     exception
 *  业务异常
 *  自定义异常
*/
@RestControllerAdvice
public class GlobalExceptionHandlerR {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandlerR.class);
    /**
     *  shiro框架如果请求为ajax返回json，普通请求跳转页面
     */
//    @ExceptionHandler(AuthorizationException.class)
//    public Object handleAuthorizationException(HttpServletRequest request, AuthorizationException e) {
//        if (ServletUtils.isAjaxRequest(request)) {
//            return ExResult.unAuthorized(PermissionUtils.getMsg(e.getMessage()));
//        } else {
//            ModelAndView modelAndView = new ModelAndView();
//            modelAndView.setViewName("error/error");
//            return modelAndView;
//        }
//    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public ExResult handleException(HttpRequestMethodNotSupportedException e) {
        log.error(e.getMessage(), e);
        return ExResult.errorTag("不支持' " + e.getMethod() + "'请求");
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ExResult notFount(RuntimeException e) {
        log.error("运行时异常:", e);
        return ExResult.errorTag("运行时异常:" + e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public ExResult handleException(Exception e) {
        log.error(e.getMessage(), e);
        return ExResult.errorTag("服务器错误，请联系管理员");
    }

    /**
     * 校验异常  参数校验
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ExResult exceptionHandler(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String errorMesssage = "";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMesssage += fieldError.getDefaultMessage() + "!";
        }
        return ExResult.errorTag(errorMesssage);
    }

    /**
     * 校验异常  端口被占用
     */
    @ExceptionHandler(value = BindException.class)
    public ExResult validationExceptionHandler(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        String errorMesssage = "";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMesssage += fieldError.getDefaultMessage() + "!";
        }
        return ExResult.errorTag(errorMesssage);
    }

    /**
     * 校验异常  违反了约束
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    public ExResult ConstraintViolationExceptionHandler(ConstraintViolationException ex) {
        Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
        Iterator<ConstraintViolation<?>> iterator = constraintViolations.iterator();
        List<String> msgList = new ArrayList<>();
        while (iterator.hasNext()) {
            ConstraintViolation<?> cvl = iterator.next();
            msgList.add(cvl.getMessageTemplate());
        }
        return ExResult.errorTag(String.join(",",msgList));
    }

    /**
     * 业务异常:自定义异常
     */
    @ExceptionHandler(BusinessExceptionR.class)
    public ExResult businessException(BusinessExceptionR e) {
        log.error(e.getMessage(), e);
        return ExResult.errorTag(e.getMessage());
    }



}
